"""
命令基础设施模块

提供命令系统的核心组件：
1. Command: 命令基类
2. CommandRegistry: 命令注册表
"""

import argparse
import logging
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple, Any
from src.base.registry import bera

class Command(ABC):
    """命令基类"""

    def __init__(self):
        self.name = self.__class__.__name__.lower().replace('command', '')
        self.group = "其他"  # 默认分组
        self.logger = logging.getLogger(self.name)
        self.config = None  # 配置对象

    @abstractmethod
    def add_arguments(self, parser: argparse.ArgumentParser) -> None:
        """添加命令特定的参数"""
        pass

    @abstractmethod
    def execute(self, args: argparse.Namespace) -> None:
        """执行命令"""
        pass

    def pre_execute(self, args: argparse.Namespace) -> None:
        """命令执行前的处理"""
        # 设置日志级别
        if args.debug:
            self.logger.setLevel(logging.DEBUG)
        elif args.verbose:
            self.logger.setLevel(logging.INFO)

        # 加载配置
        self.config = args.config_obj

        # 设置日志文件
        table_name = getattr(args, 'table', None)
        bera.logger.set_command(self.name, table_name)

    def post_execute(self, args: argparse.Namespace) -> None:
        """命令执行后的处理"""
        pass

    def get_help(self) -> Tuple[str, Optional[str]]:
        """获取命令的帮助信息"""
        doc = self.__doc__ or ""
        lines = doc.strip().split("\n")
        if not lines:
            return "", None
        
        help_text = lines[0].strip()
        epilog = "\n".join(line.strip() for line in lines[1:]).strip()
        return help_text, epilog if epilog else None

class CommandRegistry:
    """命令注册表"""

    def __init__(self):
        self._commands: Dict[str, Command] = {}
        self._groups: Dict[str, List[Command]] = {}

    def register(self, command: Command) -> None:
        """注册命令"""
        self._commands[command.name] = command

        # 添加到分组
        if command.group not in self._groups:
            self._groups[command.group] = []
        self._groups[command.group].append(command)

    def get_command(self, name: str) -> Optional[Command]:
        """获取命令"""
        return self._commands.get(name)

    def get_all_commands(self) -> List[Command]:
        """获取所有命令"""
        return list(self._commands.values())

    def get_groups(self) -> Dict[str, List[Command]]:
        """获取所有分组"""
        return self._groups